package LinkList;

public class Chain {
    private Node head = null;
    private int size = 0;

    public Chain() {
        head = new Node();
        size = 0;
    }

    public Node getHead() {
        return this.head;
    }

    public void setHead(Node head) {
        this.head = head;
    }

    public int getSize() {
        return this.size;
    }

    public void chainAll() {
        for (Node curr = head.getNext(); curr != null; curr = curr.getNext()) {
            System.out.print(" " + curr.getData().getCoef() + "y^" + curr.getData().getExp());
            System.out.print(curr.getNext() == null ? " " : "+");
        }
    }

    public boolean addAt(int i, Item elem) {
        if (i < 0 || i > size) {
            System.out.println("输入的数据不合法,请重新输入");
            return false;
        }
        Node pre, curr;
        for (pre = head; i > 0 && pre.getNext() != null; i--) {
            pre = pre.getNext();
        }
        curr = new Node(elem, pre.getNext());
        pre.setNext(curr);
        size++;
        return true;
    }

    public Chain mergeChain(Chain chain1, Chain chain2) {
        int i = 0;
        Item item = new Item();
        Node curr1, curr2;
        Chain chain3 = new Chain();
        curr1 = chain1.getHead().getNext();
        curr2 = chain2.getHead().getNext();
        while (curr1 != null && curr2 != null) {
            if (curr1.getData().getExp() > curr2.getData().getExp()) {
                item = curr1.getData();
                chain3.addAt(i, item);
                curr1 = curr1.getNext();
                i++;
            } else if (curr1.getData().getExp() < curr2.getData().getExp()) {
                item = curr2.getData();
                chain3.addAt(i, item);
                curr2 = curr2.getNext();
                i++;
            } else {
                item = new Item(curr1.getData().getCoef()
                        + curr2.getData().getCoef(), curr1.getData().getExp());
                if (item.getCoef() != 0) {
                    chain3.addAt(i, item);
                    i++;
                }
                curr1 = curr1.getNext();
                curr2 = curr2.getNext();
            }
        }
        while (curr1 != null) {
            item = curr1.getData();
            chain3.addAt(i++, item);
            curr1 = curr1.getNext();
        }
        while (curr2 != null) {
            item = curr2.getData();
            chain3.addAt(i++, item);
            curr2 = curr2.getNext();
        }
        return chain3;
    }
}
